package com.ruoyi.pay.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.pay.entity.OrderInfo;
import com.ruoyi.pay.entity.RefundInfo;
import com.ruoyi.pay.mapper.OrderInfoMapper;
import com.ruoyi.pay.mapper.RefundInfoMapper;
import com.ruoyi.pay.service.OrderInfoService;
import com.ruoyi.pay.service.RefundInfoService;
import com.ruoyi.pay.utils.OrderNoUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class RefundInfoServiceImpl extends ServiceImpl<RefundInfoMapper, RefundInfo> implements RefundInfoService {

    @Resource
    private RefundInfoMapper refundInfoMapper;

    @Resource
    private OrderInfoMapper orderInfoMapper;
    @Override
    public RefundInfo createRefundInfoForAliPay(String orderNo, String reason) {

        // 根据订单号获取订单信息
        LambdaQueryWrapper<OrderInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderInfo::getOrderNo,orderNo);
        OrderInfo orderInfo = orderInfoMapper.selectOne(wrapper);

        // 根据订单号生成退款订单
        RefundInfo refundInfo = new RefundInfo();
        refundInfo.setOrderNo(orderNo);
        refundInfo.setRefundNo(OrderNoUtils.getRefundNo());
        refundInfo.setTotalFee(orderInfo.getTotalFee());
        refundInfo.setRefund(orderInfo.getTotalFee());
        refundInfo.setReason(reason);

        refundInfoMapper.insert(refundInfo);

        return refundInfo;
    }


    @Override
    public void updateRefundForAliPay(String refundNo,String refundId, String body, String refundStatus) {
        // 根据退款单修改退款订单
        LambdaUpdateWrapper<RefundInfo> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(RefundInfo::getRefundNo,refundNo);
        // 设置update字段
        wrapper.set(RefundInfo::getRefundId,refundId);
        wrapper.set(RefundInfo::getRefundStatus,refundStatus);
        wrapper.set(RefundInfo::getContentReturn,body);

        refundInfoMapper.update(null,wrapper);
    }
}
